<template>
    <u-datetime-picker v-show="!isdisabled" @close="returnPicker = false" @cancel="returnPicker = false"
        @confirm="returnConfirm" :show="returnPicker" v-model="returnTime" mode="datetime" />
    <!-- 离开时间 -->
    <u-datetime-picker v-show="!isdisabled" @close="outPicker = false" @cancel="outPicker = false" @confirm="outConfirm"
        :show="outPicker" v-model="outTime" mode="datetime" />
    <fl-picker :type="6" @change="pickerConfirm" ref="fladvice" :pickerList="pickerColumns" />
    <fl-picker :type="6" @change="shenhePickerConfirm" ref="shenhefladvice" :pickerList="shenhepickerColumns" />
    <view class="AskApply_container">
        <scroll-view class="scroll-view" scroll-y>
            <view class="AskApply">
                <view class="cell">
                    <view class="left_title">姓名</view>
                    <view class="right_par noedit" v-if="!isUpper">{{ form.reporterName }}</view>
                    <div class="right_par" v-if="isUpper" @tap="fladvice.handleShow()">{{
                        form.reporterName || '请选择' }}
                    </div>
                </view>
                <view class="cell">
                    <view class="left_title">部门</view>
                    <view class="right_par noedit">{{ form.reporterOrgName }}</view>
                </view>
                <view class="cell">
                    <view class="left_title">联系方式</view>
                    <view class="right_par noedit">{{ form.cellPhone }}</view>
                </view>
                <view class="cell">
                    <view class="left_title">
                        <text class="star">*</text>
                        离开时间
                    </view>
                    <view class="right_par">
                        <view class="pleaseChoose" @tap="outPicker = true">
                            <text v-if="form.outTime">{{ form.outTime }}</text>
                            <text v-else style="color:#A0A0A0">请选择</text>
                            <text class="date_icon iconfont icon-24gl-calendar"></text>
                        </view>

                    </view>
                </view>
                <view class="cell">
                    <view class="left_title">
                        <text class="star">*</text>
                        返回时间
                    </view>
                    <view class="right_par">
                        <view class="pleaseChoose" @tap="returnPicker = true">
                            <text v-if="form.returnTime">{{ form.returnTime }}</text>
                            <text v-else style="color:#A0A0A0">请选择</text>
                            <text class="date_icon iconfont icon-24gl-calendar"></text>
                        </view>
                    </view>
                </view>
                <view class="cell">
                    <view class="left_title">
                        <text class="star">*</text>
                        外出地点
                    </view>
                    <view class="right_par">
                        <input class="areaInput" :disabled="isdisabled" v-model="form.dest"
                            placeholder-style="color:#a0a0a0" type="text" placeholder="请输入">
                    </view>
                </view>
                <view class="com">
                    <view class="left_title">
                        <text class="star">*</text>
                        外出事由
                    </view>
                    <view class="right_par">
                        <textarea class="textarea" auto-height :disabled="isdisabled" v-model="form.reason"
                            placeholder-style="color:#a0a0a0;" placeholder="请输入" />
                    </view>
                </view>
                <!-- <view class="upload">
                <view class="upload_con">
                    <view class="left_title">
                        附件上传
                    </view>
                    <view class="right_par">
                        <uni-file-picker :disabled="isdisabled" style="text-align: right;" v-model="form.fileList"
                            :auto-upload="true" file-mediatype="all" @select="handleUpload" />
                    </view>
                </view>
                <view class="file_list">
                    <fl-fileList @delFileItem="delFileItem" :closeShow="info != 1" :fileList="form.fileList" />
                </view>
            </view> -->
                <view class="com">
                    <view class="left_title">
                        备注
                    </view>
                    <view class="right_par">
                        <textarea class="textarea" auto-height :disabled="isdisabled" v-model="form.remark"
                            placeholder-style="color:#a0a0a0" placeholder="请输入" />
                    </view>
                </view>
                <view class="cell" style=" border-bottom: none">
                    <view class="left_title">
                        <text class="star">*</text>
                        审批人
                    </view>
                    <!-- <view v-if="form.approveName" class="approve_user">{{ form.approveName || '暂无' }}</view> -->
                    <view class="right_par" @tap="isdisabled ? null : shenhefladvice.handleShow()">
                        <text class="choose">
                            <text v-if="form.approveName" style="color: #333333;">{{ form.approveName }}</text>
                            <text v-else>请选择</text>
                        </text>
                        <text class="choose_icon  iconfont icon-youjiantou"></text>
                    </view>

                </view>
                <view class="com" v-if="advice && flag != 1">
                    <view class="left_title">
                        <text class="star">*</text>
                        审批意见
                    </view>
                    <view class="right_par">
                        <!-- :disabled="isdisabled && !sh" -->
                        <textarea :disabled="adviceDisabled" class="textarea" v-model="approveComment"
                            style="padding-top: 10rpx;height:100rpx" placeholder-style="color:#A0A0A0" placeholder="请输入" />
                    </view>
                </view>
                <!-- info == 4 =>领导审批的查看 是可以看到审批意见的 -->
                <!-- <view class="com" v-if="info == 4 || form.status == 2 || form.status == 3">
                    <view class="left_title">
                        <text class="star">*</text>
                        审批意见
                    </view>
                    <view class="right_par">
                        <textarea class="textarea" disabled v-model="approveComment"
                            style="padding-top: 10rpx;height:100rpx" placeholder-style="color:#A0A0A0" />
                    </view>
                </view> -->
            </view>
        </scroll-view>
        <view class="confire" :style="{ paddingBottom: safeAreaInsets.bottom + 'px' }">
            <view class="qx" @tap="navBack">返回</view>
            <!-- <view class="bc qd" v-if="keep" @tap="handleSubmit(1)">保存</view> -->
            <view v-if="keep" @tap="disabled ? message() : handleSubmit(2)" :class="disabled ? 'disable qd' : 'qd'">
                提交
            </view>
            <!-- 2和3代表审核过的 领导在进来 是没办法操作按钮的 -->
            <view v-if="sh" @tap="examinePass(2)" class="qd nopass">审核不通过</view>
            <view v-if="sh" @tap="examinePass(1)" class="qd">审核通过</view>
            <view v-if="nosubmit" @tap="handleDelete" class="qd nopass">删除</view>
            <view v-if="(status == 2 && type == 1)" @tap="handleRemoke" class="qd nopass">撤销</view>
        </view>
    </view>
</template>
  
<script setup>
import { ref, computed, watch } from 'vue'
import modal from '@/plugins/modal'
// import { removeZero } from '@/utils/common'
import { formatTimestamp } from '@/utils/common'
import { getUserList, deleteManage, reportAdd, revokeManage, fileUpload, prevPdf, getApproveList, manageEdit, manageExamine } from '@/api/http'
import { onLoad } from "@dcloudio/uni-app";
import store from '@/store';
const { safeAreaInsets } = uni.getSystemInfoSync()
import { checkPermi } from "@/utils/permission";
const { user } = store.getters
const form = ref({
    reason: '',//原因
    remark: '',//备注
    reporterId: '',//报备人id
    reporterName: '',//报备人姓名
    approveId: '',//审批人id
    approveName: '',//审批人姓名
    reporterOrgName: '',//报备人部门
    status: '1',
    outTime: '',//开始时间
    returnTime: '',//结束时间
    cellPhone: '',//手机号
    dest: '',//外出地点
    fileList: []

})
// 审批意见
const approveComment = ref('')
const outTime = ref(new Date().getTime())
const returnTime = ref(new Date().getTime())
const outPicker = ref(false)
const returnPicker = ref(false)
const fladvice = ref()
const shenhefladvice = ref()
const pickerColumns = ref([])
const shenhepickerColumns = ref([])
const isUpper = ref(false);
const isdisabled = ref(false)
const adviceDisabled = ref(false)
const props = defineProps(['detailData', 'status', 'flag', 'type', 'sh'])
const { status, flag } = props
switch (status) {
    case '1':
        isdisabled.value = true;
        break;
    case '2':
        isdisabled.value = true;
        adviceDisabled.value = true;
        break;
    case '3':
        isdisabled.value = true;
        adviceDisabled.value = true;
        break;
    case '4':
        isdisabled.value = true;
        break;

}


watch(() => props.detailData, (newV) => {
    handleDetailData(newV)
}, { deep: true })

const handleDelete = async () => {
    const res = await modal.confirm('您确定要删除?')
    if (res) {
        await deleteManage(form.value.id)
        // if (status == 0) {
        //     await deleteManage(form.value.id)
        // } else if (form.value.status == 2) {
        //     await deleteManage(form.value.id)
        // }
        proCommon()
    }
}
const proCommon = () => {
    modal.msgSuccess('操作成功')
    setTimeout(() => {
        uni.$emit('loadList')
        navBack()
    }, 1000);
}
const handleRemoke = async () => {
    const res = await modal.confirm(`确定撤销报备人为“${form.value.reporterName}”的数据项?`)
    if (res) {
        await revokeManage(form.value.id)
        proCommon()


    }
}
const handleDetailData = (newV) => {
    // for (let k in form.value) {
    //     if (k === 'outTime' || k === 'returnTime') {
    //         form.value[k] = removeZero(newV[k])//去点时间的最后两个0
    //     } else {
    //         form.value[k] = newV[k]
    //     }
    // }
    // let getdelay = null
    // clearInterval(getdelay)
    // getdelay = setInterval(() => {
    //     if (shenhepickerColumns.value.length > 0) {
    //         clearInterval(getdelay)
    //         const item = shenhepickerColumns.value.find(v => v.userId === newV.approveId)
    //         form.value.approveName = item.name

    //     }
    // }, 50);
    form.value = newV
    // form.value.outTime = removeZero(newV.outTime)
    // form.value.returnTime = removeZero(newV.returnTime)
    approveComment.value = newV.approveComment ? newV.approveComment : ''
    // filesVal.value = newV.fileList
    // form.value.fileList
}
const navBack = () => {
    uni.navigateBack()
}
// const handlePrevFile = async (ele) => {
//     const res = await prevPdf(ele.fileName)
// }
// 审批后 历史记录点击进去每一项是否禁用
const exam = computed(() => props.type == 1 && (form.value.status == 2 || form.value.status == 3))
// 审批意见是否显示
const advice = computed(() => (status == 1 || status == 2 || status == 3))
// 保存和提交 
const keep = computed(() => status == 0 || status === undefined)
// 领导审核且审核后不能再次审核
const sh = computed(() => status == 1 && props.type == 3)
// 历史记录中 未提交(保存)状态 
// const nosubmit = computed(() => status == 0 || form.value.status == 2)
const nosubmit = computed(() => status == 0)
// 保存按钮是否禁用
const disabled = computed(() => {
    const { outTime, returnTime, reason, approveId, dest } = form.value
    if (outTime && returnTime && reason && approveId && dest) return false
    return true
})
function getOutOthers() {
    getUserList().then((res) => {
        pickerColumns.value = res.data
        userInfoInit();
    });
}
onLoad(async () => {
    if (props.sh != 1) {
        // 审核列表 过来
        isUpper.value = checkPermi(["oa:out:others"]) && !user.admin;
        if (!isUpper.value) {
            userInfoInit();
        } else {
            getOutOthers();
        }
        const res = await getApproveList()
        shenhepickerColumns.value = res.data
    }

})
function userInfoInit() {
    const { userId, phone, org, name } = user
    form.value.reporterId = userId
    form.value.reporterName = name
    form.value.cellPhone = phone
    form.value.reporterOrgName = org.orgName
}
// const bindTextAreaBlur = (e) => {
//     approveComment.value = e.detail.value
// }
// const deleteFile = (e) => {
//     let current = e.file.uuid
//     form.value.fileList.forEach((item, index) => {
//         if (item.file.uuid === current) {
//             form.value.fileList.splice(index, 1)
//         }
//     })
// }

// const handleUpload = async (e) => {
//     let tempFilePaths = e.tempFilePaths
//     let tempFiles = e.tempFiles
//     tempFilePaths.forEach((ele, index) => {
//         uni.uploadFile({
//             url: import.meta.env.VITE_APP_BASE_API + '/resource/oss/batchUpload', //仅为示例，非真实的接口地址
//             filePath: ele,
//             name: 'files',
//             header: {
//                 Authorization: 'Bearer ' + getToken()
//             },
//             formData: {},
//             success: (res) => {
//                 let re = JSON.parse(res.data).data[0]
//                 // let obj = {
//                 //     name: re.originalName,
//                 //     extname: re.fileSuffix,
//                 //     url: re.url,
//                 // }
//                 form.value.fileList.push({ ...re, file: tempFiles[index].file, url: re.url })
//                 modal.msgSuccess('上传成功')
//             }
//         });

//     })
//     console.log(form.value.fileList, 'ssddddddddddddddddddds');

// }
const pickerConfirm = (val) => {
    let user = pickerColumns.value.find((i) => i.userId === val.userId);
    form.value.reporterName = user.name;
    form.value.reportOrgId = user.orgId;
    form.value.reporterOrgName = user.orgName;
    form.value.cellPhone = user.phone;
}

const shenhePickerConfirm = (val) => {
    form.value.approveId = val.userId
    form.value.approveName = val.name
}
const examinePass = async (t) => {
    // t==1代表 通过t==2代表不通过
    if (!approveComment.value.trim()) return modal.msgError('请输入审批意见')
    const par = {
        id: form.value.id,
        status: t == 1 ? '2' : '3',
        approveComment: approveComment.value
    }
    await manageExamine(par)
    proCommon()
}


const outConfirm = (e) => {
    form.value.outTime = formatTimestamp(e.value)
    outPicker.value = false
}
const returnConfirm = (e) => {
    form.value.returnTime = formatTimestamp(e.value)
    returnPicker.value = false

}



const handleSubmit = async (t) => {
    // 1保存  2提交
    let copyform = JSON.parse(JSON.stringify(form.value))
    if (form.value.outTime) {
        copyform.outTime = form.value.outTime + ':00'
    }
    if (form.value.returnTime) {
        copyform.returnTime = form.value.returnTime + ':00'
    }
    copyform.status = t == 1 ? '0' : '1'
    // copyform.fileList = filesVal.value
    let res;
    if (form.value.status == 0 || form.value.status == 2) {
        res = await manageEdit(copyform)
    } else {
        res = await reportAdd(copyform)
    }

    modal.msgSuccess('操作成功')
    setTimeout(() => {
        if (props.flag == 1) return uni.navigateBack()
        uni.navigateTo({ url: '/pages/submitSuccess/index?type=' + t })
    }, 1000);
}
const message = () => {
    uni.showToast({ title: '请完善必填项', icon: 'error' })
}
// const delFileItem = (index) => {
//     form.value.fileList.splice(index, 1)
// }

</script>
  
<style scoped lang="scss">
.textarea {
    font-size: 30rpx;
    padding-top: 20rpx;
    color: #333333
}

.areaInput {
    text-align: right;
    font-size: 28rpx;
    color: #333333;

}

.AskApply_container {
    display: flex;
    flex-direction: column;
    overflow: hidden;
    height: 100%;

    .scroll-view {
        flex: 1;
        height: 100%;
        overflow: hidden;

    }

    .AskApply {
        box-sizing: border-box;
        width: 94%;
        height: 100%;
        margin: 0 auto;
        background-color: #fff;
        // .upload {
        //     padding: 25rpx 10rpx;
        //     border-bottom: 2rpx solid #D6DBE3;
        //     font-size: 28rpx;
        //     color: #333333;

        //     .file_list {
        //         margin-top: 20rpx;
        //     }
        //     .upload_con {
        //         display: flex;
        //         justify-content: space-between;
        //     }
        //     .right_par {
        //         flex: 1;
        //         .file_item {
        //             position: relative;
        //             height: 60rpx;
        //             margin: 10rpx 0;
        //             line-height: 60rpx;
        //             padding-right: 80rpx;
        //             overflow: hidden;
        //             white-space: nowrap;
        //             text-overflow: ellipsis;
        //             border-bottom: 1rpx solid #f5f5f5;
        //             .closeIcon {
        //                 position: absolute;
        //                 top: 50%;
        //                 transform: translateY(-50%);
        //                 right: 5rpx;
        //                 font-size: 50rpx;
        //                 color: #333;
        //             }

        //         }

        //     }
        // }

        .cell {
            display: flex;
            justify-content: space-between;
            padding: 25rpx 10rpx;
            border-bottom: 2rpx solid #D6DBE3;
            font-size: 28rpx;
            color: #333333;

            .noedit {
                color: #333333 !important;
            }


            .left_title {
                position: relative;
                font-size: 30rpx;

                .star {
                    position: absolute;
                    color: red;
                    left: -15rpx;
                    top: 50%;
                    transform: translateY(-50%);
                    font-size: 35rpx;

                }

            }



            .right_par {
                display: flex;
                color: #a0a0a0;


                .pleaseChoose {
                    display: flex;
                    align-items: center;
                    color: #333;

                }

                .iconfont {
                    color: #97A3B7;
                    font-size: 38rpx;
                    margin-left: 5rpx;
                }

                .showTime {
                    display: flex;
                    align-items: center;
                    font-size: 29rpx;
                    color: #333333;
                }

                .choose_icon {
                    color: #8d8d8d;
                    font-size: 40rpx;
                }
            }




        }

        .com {
            padding: 25rpx 10rpx;
            border-bottom: 2rpx solid #D6DBE3;
            font-size: 28rpx;
            color: #333333;

            .left_title {
                position: relative;

                .star {
                    position: absolute;
                    color: red;
                    left: -15rpx;
                    top: 50%;
                    transform: translateY(-50%);
                    font-size: 35rpx;

                }
            }

            .right_par {
                input {
                    font-size: 28rpx;
                    margin-top: 15rpx;
                    color: #a0a0a0;
                }


            }
        }
    }

    .confire {
        position: relative;
        width: 750rpx;
        display: flex;
        justify-content: space-around;
        background-color: #fff;

        .qd,
        .qx,
        .bc {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 220rpx;
            height: 90rpx;
            border-radius: 45rpx;
            background-color: #fff;
            font-size: 28rpx;
            color: #000;

        }

        .qx {
            border: 2rpx solid #DCDCDC;
        }

        .qxw {
            width: 40%;
        }



        .qd {
            background-color: #0D80D7;
            color: #fff;
            border: none;
        }

        .disable {
            background-color: #a7c0db;
        }

        .nopass {
            background-color: red;
        }
    }
}
</style>
  